package com.turbo.cloud.core.mybatisplus;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.turbo.cloud.core.security.utils.SecurityUtil;
import com.turbo.cloud.core.trace.TraceThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


/**
 * 自定义填充公共字段
 *
 * @author zhangluning
 */
@Slf4j
@Component
@ConditionalOnClass(MetaObjectHandler.class)
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    private final static String CREATED_BY = "createdBy";
    private final static String CREATED_DATE = "createdDate";
    private final static String LAST_MODIFIED_BY = "lastModifiedBy";
    private final static String LAST_MODIFIED_DATE = "lastModifiedDate";
    private final static String DELETED_TIME_LONG = "deletedTimeLong";
    private final static String TRACE_ID = "traceId";

    @Value("${spring.application.name}")
    private String applicationName;

    /**
     * 新增填充
     *
     * @param metaObject 待填充对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 获取当前登录用户
        String username = applicationName;
        try {
            username = SecurityUtil.getCurrentUserId();
        } catch (Exception e) {
            log.error("insertFill::未获取到当前登录人信息", e);
        }
        this.fillStrategy(metaObject, CREATED_BY, username);
        this.fillStrategy(metaObject, CREATED_DATE, LocalDateTime.now());
        this.fillStrategy(metaObject, LAST_MODIFIED_BY, username);
        this.fillStrategy(metaObject, LAST_MODIFIED_DATE, LocalDateTime.now());

        final String property = metaObject.findProperty(DELETED_TIME_LONG, false);
        if (StrUtil.isNotBlank(property)) {
            this.fillStrategy(metaObject, DELETED_TIME_LONG, 0L);
        }
    }

    /**
     * 更新填充
     *
     * @param metaObject 待填充对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        // 获取当前登录用户
        String username = applicationName;
        try {
            username = SecurityUtil.getCurrentUserId();
        } catch (Exception e) {
            log.error("updateFill::未获取到当前登录人信息", e);
        }
        setFieldValByName(LAST_MODIFIED_BY, username, metaObject);
        setFieldValByName(LAST_MODIFIED_DATE, LocalDateTime.now(), metaObject);
        setFieldValByName(TRACE_ID, TraceThreadLocal.getTraceId(), metaObject);
    }
}
